// 数据格式处理层
const querystring = require('querystring');
const postData = require('./src/utils/postData');
const userRouter = require('./src/router/userRouter');
const timeRouter = require('./src/router/timeRouter');
const appointmentRouter = require('./src/router/appointmentRouter');
const sessionsRouter = require('./src/router/sessionsRouter');
const { notFoundModel, successModel } = require('./src/utils/resModel');
const formatRes = require('./src/utils/formatRes');
// 读取图片
const fs = require('fs');
const path = require('path');


// req（网址）请求数据res返回值
const serverHandle = async (req, res) => {

    // 设置web编码格式
    res.setHeader("Content-Type", "application/json");

    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // 解决跨域问题
    res.setHeader("Access-Control-Allow-Origin", "*");

    res.setHeader("Access-Control-Allow-Headers","Content-Type")

    if (req.method === "OPTIONS") {
        formatRes(res, successModel());
        return;
    }

    if (req.method === "GET") {
        // url格式化 切割多余的 '/'  query是自己定义的
        req.query = querystring.parse(req.url.slice(req.url.indexOf("?") + 1));
    } else {
        try {
            // post的数据放在body里面
            req.body = await postData(req);
        } catch (error) {
            res.end("解析数据错误!!!");
        }
    }
    // 切割地址栏？后的数据然后后面进行数据判断  0是路径,1是参数
    req.path = req.url.split("?")[0];

    // 嵌入router的文件，并且进行转译
    const userRus = await userRouter(req, res);
    if (userRus) {
        formatRes(res, userRus);
    };

    const timeRus = await timeRouter(req, res);
    (timeRus) && (formatRes(res, timeRus));

    const appointmentRus = await appointmentRouter(req, res);
    (appointmentRus) && (formatRes(res, appointmentRus));

    const sessionsRus = await sessionsRouter(req, res);
    (sessionsRus) && (formatRes(res, sessionsRus));


    // // 读取图片QRCODE
    // if (req.path.includes("/src/qrcode")) {
    //     res.setHeader("Content-Type", "text/plain");
    //     res.end(await getBase64(req.path) )
    //     console.log(path.join(__dirname, req.path));
    //     // file.pipe(res);
    //     let str = await getBase64(req.path);
    //     res.end(str);
    // } else {
    //     res.end(JSON.stringify(notFoundModel()));
    // }
    // //数据发生错误返回的结果'404'等
    // formatRes(res, notFoundModel());

    // 读取图片QRCODE
    if (req.path.includes("/src/qrcode")) {
        if (req.query.mode === "look") {
            res.setHeader("Content-Type", "text/plain");
            formatRes(res, successModel({
                file: await getBase64(req.path)
            }));
        } else {
            res.end(await getBase64(req.path));
        }
    } else {
        formatRes(res, notFoundModel());
        //数据发生错误返回的结果'404'等
    }
}

// 异步变同步
function getBase64(_path) {
    return new Promise(resolve => {
        let str = "";
        // 创建空字符串把读流拼接起来
        let file = fs.createReadStream(path.join(__dirname, _path));
        // 创建读文件的读流
        file.on("data", (chunk) => {
            str += chunk.toString('base64');
        })
        file.on("end", () => {
            // console.log("data:image/png;base64," + str);
            resolve("data:image/png;base64," + str);
        })
    })
}

// 处理端口层
module.exports = serverHandle;